/**
 * @version		$Id: profiles.js 101 2011-02-25 18:39:15Z happy_noodle_boy $
 * @package		JCE
 * @copyright	Copyright (C) 2009 Ryan Demmer. All rights reserved.
 * @license		GNU/GPL
 * This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 */
(function($) {	
    // Create Profiles object
	$.jce.Profiles = {
        initList : function() {
            $('span.profiles-enable, span.profiles-disable').click( function() {
                var el = this, task = 'enable';
                if (this.hasClass('profiles-enable')) {
                    task = 'disable';
                } else {
                    task = 'enable';
                }
                $(this).addClass('loading');
                $(this).parents('tr').find('input:checkbox[name^=cid]').attr('checked', true);

                submitform(task);
            });
        },
        initEdit : function(options) {
            var self = this;

            // Tabs
            $('#tabs').tabs();

            // Buttons
            $('button#user-group-add').button({
                icons : {
                    primary : 'icon-add'
                }
            }).click( function(e) {
                e.preventDefault();
                $('select#types').children().attr('selected', true);
                return false;
            });
            
            $('button#user-group-remove').button({
                icons : {
                    primary : 'icon-remove'
                }
            }).click( function(e) {
                e.preventDefault();
                $('select#types').children(':selected').attr('selected', false);
                return false;
            });
            // users list
            $('button#users-add').button({
                icons : {
                    primary : 'icon-add'
                }
            });

            $('button#users-remove').button({
                icons : {
                    primary : 'icon-remove'
                }
            }).click( function(e) {
                e.preventDefault();
                $('select#users').children(':selected').remove();
                return false;
            });
            $('button#layout-legend').button({
                icons : {
                    primary : 'icon-legend'
                }
            });

            // Editable Selects

            $( "select.editable, select.combobox" ).combobox(options.combobox);

            $("#tabs-editor, #tabs-plugins").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
            $("#tabs-editor li, #tabs-plugins li").removeClass('ui-corner-top').addClass('ui-corner-left');

            // Color Picker
            $('input.color').colorpicker(options.colorpicker);

            // Extension Mapper
            $('select.extensions, input.extensions, textarea.extensions').ExtensionMapper(options.extensions);

            // Layout
            this.createLayout();

            // Check list
            $('select.checklist').checkList();

            $('input.autocomplete').each( function() {
                var el = this, v = $(el).attr('placeholder') || '';
                $(el).removeAttr('placeholder');
                $(el).autocomplete({
                    source: v.split(',') || []
                });
            });
            
            $('input[name="components-select"]').click( function() {
            	$('select#components').attr('disabled', (this.value == 'all')).children('option:selected').removeAttr('selected');
            });
            
            $('#editor_paramswidth').change( function() {
                v = this.value;
                if (v && /%/.test(v)) {
                    return;
                } else {
                    if (v) {
                        this.value = v = parseInt(v);
                    } else {
                        v = 600;
                    }
                    $('span.sortableListSpan').width(v);
                    $('div.widthMarker').width(v).html(v + 'px');
                }
            });
            
            $('#editor_paramsheight').change( function() {
                this.value = this.value.replace(/[^0-9%]/g, '');
            });

            $('ul#profileAdditionalFeatures input:checkbox').click( function() {
                self.setPlugins();
            });
        },
        
        onSubmit : function() {
            $('div#tabs-editor, div#tabs-plugins').find(':input[name]').each( function() {
                // disable blank or placeholder values
                if ($(this).val() === '' || $(this).hasClass('placeholder')) {
                    $(this).attr('disabled', 'disabled');
                }
            });
        },

        createLayout : function() {
        	var self = this;
        	
        	// List items
            $("ul.sortableList").sortable({
                connectWith	: 'ul.sortableList',
                axis		: 'y',
                tolerance	: 'intersect',
                handle		: 'span.sortableHandle',
                update		: function(event, ui) {
            		self.setRows();
            		self.setPlugins();
                },
                placeholder	: 'sortableListItem row-highlight',
                forcePlaceholderSize: true
            }).disableSelection();

            $('ul.sortableRow').sortable({
                connectWith	: 'ul.sortableRow',
                tolerance	: 'intersect',
                update: function(event, ui) {
            		self.setRows();
            		self.setPlugins(); 
                },
                placeholder	: 'sortableRowItem item-highlight',
                forcePlaceholderSize: true
            }).disableSelection();
        },
        
        setRows : function() {
        	var rows = [];
            
            $('ul.sortableRow:has(li)', '#profileLayout').each( function() {
                rows.push($.map($('li.sortableRowItem', $(this)), function(el) {
                	if ($(el).hasClass('spacer')) {
                        return 'spacer';
                    }
                    return $(el).data('name');
                }).join(','));
            });
            
            $('input[name="rows"]').val(rows.join(';'));
        },
        
        /**
         * show / hide parameters for each plugin
         * @param {Object} id
         * @param {Object} state
         */
        setPlugins: function() {
            var self = this, plugins = [];

            $('ul.sortableRow li.plugin', '#profileLayout').each( function() {
            	plugins.push($(this).data('name'));
            });
            
            $('ul#profileAdditionalFeatures input:checkbox:checked').each(function() {
            	plugins.push($(this).val());
            });
            
            // set plugins
            $('input[name="plugins"]').val(plugins.join(','));
            
            self.setParams(plugins);
        },
        
        setParams : function(plugins) {
        	var $tabs = $('div#tabs-plugins');
        	
        	$('div.ui-tabs-panel', 'div#tabs-plugins').each(function(i) {
        		var name = $(this).data('name');
        		
        		var s = $.inArray(name, plugins) != -1;
        		// disable forms in tab panel
        		$(':input[name]', $(this)).attr('disabled', !s);

        		if (!s) {        			        			
        			if ($tabs.tabs('option', 'selected') == i) {            			
            			var n = 0, x = $tabs.tabs('option', 'disabled');

                        while (i == n) {
                            n++;
                            
                            if ($.inArray(n, x) != -1) {
                            	n++;
                            }
                        }

                        // select another tab if current tab is this one
                        $tabs.tabs('select', n);
                    }
            		
            		// disable the tabs
            		$tabs.tabs('disable', i);
        			
        		} else {        			
        			$tabs.tabs('enable', i);
        		}
            });
        }
    }
    // End Groups
})(jQuery);
